/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

/**
 * 获取全部片区下拉框
 *  */
import React, { useCallback, forwardRef, useEffect, useState } from 'react';
import { Select, Spin } from 'antd';
import { getTownList } from '@/services/zyAcount';

const { Option } = Select;

const TownSelect = forwardRef((props, ref) => {
  const { value, onSelect, onChange, type, pid, ...restProps } = props;
  const [list, setList] = useState([]);
  const [loading, setLoading] = useState(false);

  const filterOption = useCallback(
    (input, option) =>
      option.props.children &&
      option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0,
    [],
  );

  useEffect(
    () => {
      if (pid) {
        setLoading(true);
        getTownList({ pid }).then(townList => {
          setList([...townList]);
          setLoading(false);
        });
      }
    },
    [pid],
  );

  const handleSelect = useCallback(
    (val, options) => {
      onSelect && onSelect(val, options);
      onChange && onChange(val);
    },
    [onSelect],
  );

  return (
    <Select
      ref={ref}
      style={{ width: '100%' }}
      placeholder="选择乡镇"
      showSearch
      filterOption={filterOption}
      value={value}
      onSelect={handleSelect}
      {...restProps}
    >
      {loading ? (
        <Option disabled value="loading">
          <Spin />
        </Option>
      ) : (
        list.map(({ name, code }) => (
          <Option key={code} value={name} name={name}>
            {name}
          </Option>
        ))
      )}
    </Select>
  );
});

export default TownSelect;
